class BlogsController < ApplicationController
  before_action :set_obj, only: %i(show edit update destroy follow_blog cancel_follow_blog)
  def index
    page = params[:page] || 1
    per_page = params[:per_page] || 30
    @objs = @model.paginate(page: page, per_page: per_page).includes(:comments)
  end

  def my_followed
    page = params[:page] || 1
    per_page = params[:per_page] || 30
    @objs = @model.joins(:followed).where(blog_follows: {user_id: @current_user_id}).paginate(page: page, per_page: per_page).includes(:comments)
  end

  def my_unfollowed
    page = params[:page] || 1
    per_page = params[:per_page] || 30
    @objs = @model.joins(:unfollowed).where(blog_follows: {user_id: @current_user_id}).paginate(page: page, per_page: per_page).includes(:comments)
  end

  def create
    @blog = @current_user.blogs.build(permitted_params)
    if @blog.save
      flash[:success] = "The blog has been created!"
      redirect_to blogs_path
    else
      render 'static_pages/home'
    end
  end

  def follow_blog
    if @current_user_id
      @follow = @obj.blog_follows.find_or_initialize_by(user_id: @current_user_id)
      @follow.status = true
    end
    respond_to do |format|
      format.json {render json: {flag: (@follow.try(:save) ? true : false), followed_num: @obj.followed.count, unfollowed_num: @obj.unfollowed.count, id: @obj.id}}
    end
  end

  def cancel_follow_blog
    if @current_user_id
      @follow = @obj.blog_follows.where(user_id: @current_user_id).first
    end
    respond_to do |format|
      format.json {render json: {flag: (@follow.try(:update, status: false) ? true : false), followed_num: @obj.followed.count, unfollowed_num: @obj.unfollowed.count, id: @obj.id}}
    end
  end
end
